package com.tsxy.common.intercepter;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.tsxy.Exception.MyException;
import com.tsxy.common.Constants;
import com.tsxy.entity.User;
import com.tsxy.service.IUserService;
import com.tsxy.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtIntercepter implements HandlerInterceptor {

    @Autowired
    IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if ( ! (handler instanceof HandlerMethod) ){
            return true;
        }
        if (StrUtil.isBlank(token)){
            throw  new MyException(Constants.CODE_401,"无Token，请重新登录");
        }
        //获取token中的数据
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException e){
            throw  new MyException(Constants.CODE_401,"Token验证失败，请重新登录");
        }
        //根据Token中的userId查询出数据库中的用户信息
        User user = userService.getById(userId);
        if (user == null){
            throw new MyException(Constants.CODE_401,"没有该用户，请重新登录");
        }
        // 用户密码 加签 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证Token
        } catch (JWTVerificationException e) {
            throw new MyException(Constants.CODE_401,"Token验证错误");
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
